<template>
  <div class="editor-container">
    <div class="editor-body">
      <div class="form-row">
        <div class="form-item full-width">
          <label><span class="required">*</span> 题目</label>
          <div class="rich-editor" :class="{ 'fullscreen-mode': expanded }">
            <RichTextEditor v-model="editorContent" placeholder="添加题目" :autofocus="true" :maxLength="5000"
              @change="onContentChange" />

          </div>
        </div>
        <div class="form-item full-width">
          <label><span class="required">*</span> 解析</label>
          <div class="rich-editor" :class="{ 'fullscreen-mode': expanded }">
            <QuillEditor v-model="analyseContent" content-type="html" :height="'130px'" :max-length="5000"
              :upload-image="handleImageUpload" @exceed-limit="handleLimitExceed" />
          </div>
        </div>
      </div>
      <div class="form-row">
        <div class="form-item full-width">
          <label><span class="required">*</span> 难度等级</label>
          <div class="difficulty-options">
            <button v-for="(level, index) in difficultyLevels" :key="index"
              :class="['difficulty-btn', questionData.difficulty === level.value ? 'active' : '']"
              @click="questionData.difficulty = level.value">
              {{ level.label }}
            </button>
          </div>
        </div>
      </div>
      <!-- 单选题和多选题显示选项列表 -->
      <div class="options-section">
        <div style="display: flex;">
          <h3 style="font-size: 1.1rem;">答案</h3>
          <h3 style="margin-left: 20px">选项列表</h3>
        </div>

        <div v-for="(option, index) in questionData.options" :key="index" class="option-item">
          <div class="option-label">
            <div>{{ String.fromCharCode(65 + index) }}</div>
            <div >
              <input
      type="checkbox"
      :id="'answer' + index"
      :checked="option.checked"
      @click="selectOption(index)"
      class="hidden-checkbox"
    />
    <!-- 自定义复选框 -->
    <label :for="'answer' + index" class="styled-checkbox">
      <!-- 显示选中状态 -->
      <span v-if="option.checked" class="checkmark">✔</span>
    </label>
            </div>

          </div>
          <div class="option">
          <div class="option-content">
            <div class="rich-editor" :class="{ 'selected': option.checked }">
              <QuillEditor v-model="option.content" content-type="html" :height="'150px'" :max-length="5000"
                :upload-image="handleImageUpload" @exceed-limit="handleLimitExceed" />
            </div>

          </div>
          <div class="option-actions">
              <button class="option-btn add" @click="addOption">+</button>
              <button class="option-btn remove" @click="removeOption(index)"
                :disabled="questionData.options.length <= 1">
                -
              </button>
            </div>
            </div>
        </div>
      </div>
    </div>
    <div class="editor-footer">
      <button class="btn-cancel">取消</button>
      <button class="btn-confirm" @click="confirm">确认</button>
    </div>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, defineProps, watch, defineEmits } from 'vue';
import RichTextEditor from '@/components/commont/RichTextEditor.vue';
import QuillEditor from '@/components/commont/QuillEditor.vue';
import { QuestionService } from '@/api/questionApi';
import Loading from '@/components/commont/Loading.vue';
import { dialogProps } from 'element-plus';
import { dataType } from 'element-plus/es/components/table-v2/src/common.mjs';
import { id } from 'element-plus/es/locale/index.mjs';
const loading = ref(false);
const selectedOptions = ref([]);
// 难度等级
const difficultyLevels = [
  { label: '简单', value: '0' },
  { label: '较容易', value: '1' },
  { label: '一般', value: '2' },
  { label: '较难', value: '3' },
  { label: '非常难', value: '4' }
];

const emit = defineEmits(['emitData'])



// 问题数据
// const questionData = reactive({
//   title: '',
//   difficulty: '0',
//   options: [
//     { content: '',checked:false }
//   ],
//   selectedOptionIndex: null, // 当前选中的选项索引
//   judgmentAnswer: 'true',
//   shortAnswer: '',
//   languageType: 'chinese',
//   timeLimit: 60
// });

const props = defineProps({
  questionData: {
    type: Object,
    default: {
      id: '',
      title: '',
      difficulty: '0',
      options: [
        { content: '', checked: false }
      ],
      selectedOptionIndex: null, // 当前选中的选项索引
      judgmentAnswer: 'true',
      shortAnswer: '',
      languageType: 'chinese',
      timeLimit: 60
    }
  },
  editorContent: {
    type: String,
    default: '<p></p>'
  },
  analyseContent: {
    type: String,
    default: '<p></p>'
  }
})
const editorContent = ref(props.editorContent);
const questionData = reactive(props.questionData);
const analyseContent = ref(props.analyseContent);
watch(
  () => props.questionData,
  (newVal) => {
    // 更新某个对象的属性
    Object.assign(questionData, newVal);
  }
);

// // 监听 props.editorContent
// watch(
//   () => props.editorContent,
//   (newVal) => {
//     // 更新 editorContent 的值
//     editorContent.value = newVal;
//   }
// );


const getContent = () => {
  console.log('Editor content:', editorContent.value);
  return editorContent.value;
};
function selectOption(selectedIndex) {
  // 遍历所有选项，重置 checked 状态
  this.questionData.options.forEach((option, index) => {
    option.checked = index === selectedIndex;
  });
}
const onContentChange = (content) => {
  console.log('Content changed:', editorContent.value);
};
// 添加全屏状态
const expanded = ref(false)

// 编辑器状态
const editorState = reactive({
  fontSize: '12pt',
  isFullscreen: false
});
const selectedFontSize = ref(editorState.fontSize)

// 编辑器引用
const titleEditor = ref(null);
const answerEditor = ref(null);
const optionEditors = reactive({});



// 添加选项
const addOption = () => {
  questionData.options.push({ content: '' });
  // 等待DOM更新后设置新选项的编辑器
  nextTick(() => {
    const index = questionData.options.length - 1;
    if (optionEditors[index]) {
      optionEditors[index].focus();
    }
  });
};

// 删除选项
const removeOption = (index) => {
  if (questionData.options.length > 1) {
    questionData.options.splice(index, 1);
    if (this.selectedOptionIndex === index) {
      this.selectedOptionIndex = null;
    }
  }
};


function removeCircularReferences(obj, seen = new WeakSet()) {
  if (typeof obj !== 'object' || obj === null) return obj;

  if (seen.has(obj)) return '[Circular]'; // 标记循环引用
  seen.add(obj);

  if (Array.isArray(obj)) {
    return obj.map(item => removeCircularReferences(item, seen));
  }

  const result = {};
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      result[key] = removeCircularReferences(obj[key], seen);
    }
  }
  return result;
}

const confirm = async () => {
  if (data.quType == 1) {
    if (!validateOptions(data.options)) {
      return;
    }
    if (data.content.trim() == '<p></p>') {
      alert('题目内容为空')
      return;
    }
  }


  console.log('题目内容:', props.questionData);
  const data = {
    difficulty: questionData.difficulty,
    content: editorContent.value,
    options: questionData.options,
    quType: 1,
    id: questionData.id,

    analyse: analyseContent.value
  }
  emit('emitData', data)
};

const validateOptions = (options) => {
  // 1. 检查 options 是否为数组
  if (!Array.isArray(options)) {
    alert('options 不是数组')
    return false;
  }

  // 2. 检查数组长度是否为 2
  if (options.length <= 2) {
    alert('至少包含两个选项')
    return false;
  }

  // 3. 检查所有 content 是否为空字符串
  for (let option of options) {
    if (option.content.trim() === '') {
      alert('选项内容不能为空')
      return false;
    }
  }

  return true;
};



// 组件挂载后初始化
onMounted(() => {
  // 初始化编辑器

});
</script>

<style scoped>
.editor-container {
  max-width: 100%;
  margin: 0 auto;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  font-family: Arial, sans-serif;

}





.expand-button,
.close-button {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
}

.editor-body {
  padding: 20px;
  flex: 1;
}

.form-row {
  display: flex;
  margin-bottom: 20px;
  flex-direction: column;
  gap: 20px;
}

.form-item {
  flex: 1;
}

.full-width {
  width: 100%;
}

label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #333;
}

.required {
  color: #f56c6c;
  margin-right: 2px;
}

.input-control {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.rich-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  width: 100%;
}

.editor-toolbar {
  display: flex;
  flex-wrap: wrap;
  gap: 1px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
  padding: 6px 8px;
}

.font-size-select {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 14px;
  margin-right: 4px;
}

.toolbar-btn {
  background: none;
  border: none;
  padding: 5px 8px;
  cursor: pointer;
  border-radius: 4px;
  font-size: 14px;
}

.toolbar-btn:hover {
  background-color: #e6e6e6;
}

.upload-btn {
  background-color: #4169e1;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  cursor: pointer;
  font-size: 14px;
  margin-left: auto;
}

.editor-content {
  width: 100%;
  min-height: 100px;
  padding: 12px;
  border: none;
  outline: none;
  line-height: 1.5;
  font-family: Arial, sans-serif;
  box-sizing: border-box;
  background-color: #fff;
}

.difficulty-options {
  display: flex;
  gap: 5px;
}

.difficulty-btn {
  flex: 1;
  padding: 8px 16px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.difficulty-btn:hover {
  border-color: #c6e2ff;
  color: #409eff;
}

.difficulty-btn.active {
  background-color: #4169e1;
  border-color: #4169e1;
  color: white;
}

.options-section {
  margin-top: 30px;
  height: 100%;
}

.options-section h3 {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  color: #333;
}

.option-item {
  display: flex;
  margin-bottom: 12px;
  align-items: center;
}

.rich-editor.selected {
  background-color: #8bec5a2e;
  border-radius: 20px;
}

.option-label {
  width: 30px;
  margin-right: 10px;
  padding-top: 12px;
  font-size: 1.1rem;
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;

}

.option-content {
  flex: 1;
  display: flex;

}

.option-actions {
  display: flex;
  flex-direction: column;
  gap: 5px;

  margin-left: 10px;
  padding-top: 20px;
  height: 100%;
  align-items: center;

}

.option-btn {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2rem;

}

.option-btn.add {
  color: #67c23a;

}

.option-btn.remove {
  color: #f56c6c;
}

.option-btn:hover {
  background-color: var(--hover-color);
}

.option-btn:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}





.editor-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 20px;
  border-top: 1px solid #e0e0e0;
}

.btn-cancel {
  padding: 8px 16px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
}

.btn-confirm {
  padding: 8px 16px;
  background-color: #4169e1;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
}

.btn-cancel:hover {
  border-color: #c6e2ff;
  color: #409eff;
}

.btn-confirm:hover {
  background-color: #365cc5;
}

.option{
  display: flex ;
  flex: 1;
  height: 100%;
}
/* 全屏模式样式 */
.rich-editor.fullscreen-mode {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  background: white;
  height: 100vh !important;
  width: 100vw !important;
  border-radius: 0;
}


.rich-editor {
  position: relative;
  border: 1px solid #ccc;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.editor-content {
  min-height: 150px;
  max-height: 400px;
  padding: 12px;
  overflow-y: auto;
}

/* 全屏时内容区域高度调整 */
.fullscreen-mode .editor-content {
  height: calc(100vh - 50px) !important;
  /* 50px为工具栏大致高度 */
  max-height: none !important;
}

.toolbar-btn {
  padding: 6px 10px;
  background: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.toolbar-btn:hover {
  background: #f0f0f0;
}

.icon-fullscreen {
  display: inline-block;
  width: 20px;
  height: 20px;
  text-align: center;
}

.editor-content span {
  font-size: inherit !important;
}

.font-size-select {
  padding: 4px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-right: 8px;
}
.hidden-checkbox {
  display: none; /* 完全隐藏 */
}

/* 自定义复选框容器 */
.custom-checkbox {
  display: inline-block;
  position: relative;
  cursor: pointer;
  font-size: 15rem; /* 控制整体大小 */
}

/* 自定义复选框样式 */
.styled-checkbox {
  width: 1em; /* 大小与字体一致 */
  height: 1em;
  border: 2px solid #ccc; /* 边框颜色 */
  border-radius: 4px; /* 圆角 */
  background-color: #fff; /* 背景颜色 */
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease; /* 添加过渡效果 */
}

/* 鼠标悬停时的样式 */
.styled-checkbox:hover {
  border-color: #007bff; /* 边框变色 */
}

/* 选中状态的样式 */
.hidden-checkbox:checked + .styled-checkbox {
  background-color: #007bff; /* 背景变蓝 */
  border-color: #007bff; /* 边框变蓝 */
}

/* 对勾符号样式 */
.checkmark {
  color: #fff; /* 对勾颜色 */
  font-size: 0.6em; /* 对勾大小 */
  font-weight: bold;
}
</style>
